//
//  UIView+XMExtension.swift
//  AnneKit-Swift
//
//  Created by 寜小陌 on 2021/3/3.
//  Copyright © 2021 宁小陌. All rights reserved.
//

import Foundation
import UIKit

enum kViewCornerRadiusType {
    /// 设置下左角 圆角半径
    case kViewCornerRadiusTypeBottomLeft
    /// 设置下右角 圆角半径
    case kViewCornerRadiusTypeBottomRight
    /// 设置上左角 圆角半径
    case kViewCornerRadiusTypeTopLeft
    /// 设置下右角 圆角半径
    case kViewCornerRadiusTypeTopRight
    /// 设置下左、下右角 圆角半径
    case kViewCornerRadiusTypeBottomLeftAndBottomRight
    /// 设置上左、上右角 圆角半径
    case  kViewCornerRadiusTypeTopLeftAndTopRight
    /// 设置下左、上左角 圆角半径
    case kViewCornerRadiusTypeBottomLeftAndTopLeft
    /// 设置下右、上右角 圆角半径
    case kViewCornerRadiusTypeBottomRightAndTopRight
    /// 设置上左、上右、下右角 圆角半径
    case kViewCornerRadiusTypeBottomRightAndTopRightAndTopLeft
    /// 设置下右、上右、下左角 圆角半径
    case kViewCornerRadiusTypeBottomRightAndTopRightAndBottomLeft
    /// 设置全部四个角 圆角半径
    case kViewCornerRadiusTypeAllCorners
}

// MARK: -- 添加方法 --
extension UIView {
    /// 将一个UIView视图转为图片
    public func nxm_makeImage() -> UIImage {
        let size = self.bounds.size
        /**
         第一个参数表示区域大小。
         第二个参数表示是否是非透明的。如果需要显示半透明效果，需要传NO，否则传YES。
         第三个参数就是屏幕密度了
         */
        UIGraphicsBeginImageContextWithOptions(size, true, UIScreen.main.scale)
        self.layer.render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    /// 设置圆角
    func nxm_setViewBorderColor(cornerRadius:CGFloat = 5, color:UIColor = .clear) {
        self.layer.masksToBounds = true
        self.layer.cornerRadius = cornerRadius
        self.layer.borderColor = color.cgColor;
        self.layer.borderWidth = 1;
        self.layer.shouldRasterize = true
        self.layer.rasterizationScale = self.layer.contentsScale
    }
    
    func nxm_setViewBorderWidth(_ borderWidth:CGFloat = 1, _ borderColor:UIColor) {
        self.layer.borderColor = borderColor.cgColor;
        self.layer.borderWidth = borderWidth;
    }
    
    /// 设置单独某个位置圆角（make: 圆角范围，corners: 设置圆角位置）
    class func nxm_changeMaskLayer(rect:CGRect ,make: CGSize, corners: UIRectCorner) -> CAShapeLayer {
        let maskPath = UIBezierPath(roundedRect: rect, byRoundingCorners: corners, cornerRadii: make)
        let maskLayer = CAShapeLayer()
        maskLayer.frame = rect
        maskLayer.path = maskPath.cgPath
        return maskLayer
    }
    
    /// 通过贝塞尔曲线，裁切四个边的任意几个的圆角
    public func nxm_clipCorners(_ corner:UIRectCorner, cornerRadii:CGSize) {
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corner, cornerRadii: cornerRadii)
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    func nxm_setViewCornerRadiusType(cornersType: kViewCornerRadiusType = .kViewCornerRadiusTypeAllCorners, radius:CGFloat = 5.0) {
        var corners = UIRectCorner()
        let cornerRadii = CGSize()
        switch cornersType {
        case .kViewCornerRadiusTypeBottomLeft:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue))
            break
        case .kViewCornerRadiusTypeBottomRight:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomRight.rawValue))
            break
        case .kViewCornerRadiusTypeTopLeft:
            corners = UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue))
            break
        case .kViewCornerRadiusTypeTopRight:
            corners = UIRectCorner(rawValue: (UIRectCorner.topRight.rawValue))
            break
        case .kViewCornerRadiusTypeBottomLeftAndBottomRight:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue) | (UIRectCorner.bottomRight.rawValue))
            break
        case .kViewCornerRadiusTypeTopLeftAndTopRight:
            corners = UIRectCorner(rawValue: (UIRectCorner.topLeft.rawValue) | (UIRectCorner.topRight.rawValue))
            break
        case .kViewCornerRadiusTypeBottomLeftAndTopLeft:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomLeft.rawValue) | (UIRectCorner.topLeft.rawValue))
            break
        case .kViewCornerRadiusTypeBottomRightAndTopRight:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomRight.rawValue) | (UIRectCorner.topRight.rawValue))
            break
        case .kViewCornerRadiusTypeBottomRightAndTopRightAndTopLeft:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomRight.rawValue) | (UIRectCorner.topRight.rawValue) | (UIRectCorner.topLeft.rawValue))
            break
        case .kViewCornerRadiusTypeBottomRightAndTopRightAndBottomLeft:
            corners = UIRectCorner(rawValue: (UIRectCorner.bottomRight.rawValue) | (UIRectCorner.topRight.rawValue) | (UIRectCorner.bottomLeft.rawValue))
            break
        case .kViewCornerRadiusTypeAllCorners:
            corners = UIRectCorner(rawValue: (UIRectCorner.allCorners.rawValue))
            break
        }
        let maskPath = UIBezierPath(roundedRect: self.bounds, byRoundingCorners: corners, cornerRadii: cornerRadii)
        let maskLayer = CAShapeLayer()
        maskLayer.frame = self.bounds
        maskLayer.path = maskPath.cgPath
        self.layer.mask = maskLayer
    }
    
    /// 设置阴影
    func nxm_setViewShadowColor(shadowOpacity:Float,shadowColor:UIColor,shadowOffset:CGSize) {
        self.layer.shadowOpacity = shadowOpacity
        self.layer.shadowColor = shadowColor.cgColor
        self.layer.shadowOffset = shadowOffset
    }
    
    /// 在view中获取view所在控制器
    func nxm_getViewController() -> UIViewController? {
        var next:UIView? = self
        repeat{
            if let nextResponder = next?.next {
                if nextResponder.isKind(of: UIViewController.self) {
                    return (nextResponder as! UIViewController)
                }
            }
            next = next?.superview
        }while next != nil
        return nil
    }
    
    /// 移除所有子视图
    public func nxm_removeAllChildView() {
        subviews.forEach { $0.removeFromSuperview() }
    }
    
    /// 移除layer 根据名称（layerName: name）
    public func nxm_removeLayer(by names:[String]) {
        if self.layer.sublayers != nil {
            for item in self.layer.sublayers! {
                let name = item.name ?? ""
                if names.contains(name) {
                    item.removeFromSuperlayer()
                }
            }
        }
    }
    /// 获取视图的控制器
    public func nxm_getSuperController() -> UIViewController {
        var next = superview
        while (next != nil) {
            let nextResponder = next?.next
            if (nextResponder is UIViewController) {
                return (nextResponder as? UIViewController) ?? UIViewController()
            }
            next = next?.superview
        }
        return UIViewController()
    }
}


extension UIView {
    
    /// view截图为image
    public func nxm_toImage () -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0.0)
        drawHierarchy(in: bounds, afterScreenUpdates: true)
        let img = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return img!
    }
}

// MARK: -- 点击方法 --
extension UIView {
    /// 针对label或view的单击事件
    public func nxm_addTapGesture(tapNumber: Int = 1, target: AnyObject, action: Selector) {
        let tap = UITapGestureRecognizer(target: target, action: action)
        tap.numberOfTapsRequired = tapNumber
        addGestureRecognizer(tap)
        isUserInteractionEnabled = true
    }
    
    public func nxm_addTapGesture(tapNumber: Int = 1, action: ((UITapGestureRecognizer) -> Void)?) {
        let tap = WhenTappedBlock(tapCount: tapNumber, fingerCount: 1, action: action)
        addGestureRecognizer(tap)
        isUserInteractionEnabled = true
    }
}

class WhenTappedBlock: UITapGestureRecognizer {
    private var tapAction: ((UITapGestureRecognizer) -> Void)?

    public override init(target: Any?, action: Selector?) {
        super.init(target: target, action: action)
    }

    public convenience init (
        tapCount: Int = 1,
        fingerCount: Int = 1,
        action: ((UITapGestureRecognizer) -> Void)?) {
            self.init()
            self.numberOfTapsRequired = tapCount
            #if os(iOS)
            self.numberOfTouchesRequired = fingerCount
            #endif

            self.tapAction = action
            self.addTarget(self, action: #selector(WhenTappedBlock.didTap(_:)))
    }

    @objc open func didTap (_ tap: UITapGestureRecognizer) {
        tapAction? (tap)
    }
}



//MARK:-- 添加存储属性 --
extension UIView{
    
    convenience init(x: CGFloat, y: CGFloat, w: CGFloat, h: CGFloat) {
        self.init(frame: CGRect(x: x, y: y, width: w, height: h))
    }
    
    public var x: CGFloat {
        get {
            return self.frame.origin.x
        } set(value) {
            self.frame = CGRect(x: value, y: self.y, width: self.width, height: self.height)
        }
    }

    public var y: CGFloat {
        get {
            return self.frame.origin.y
        } set(value) {
            self.frame = CGRect(x: self.x, y: value, width: self.width, height: self.height)
        }
    }
  
    public var width: CGFloat {
        get {
            return self.frame.size.width
        } set(value) {
            self.frame = CGRect(x: self.x, y: self.y, width: value, height: self.height)
        }
    }

    public var height: CGFloat {
        get {
            return self.frame.size.height
        } set(value) {
            self.frame = CGRect(x: self.x, y: self.y, width: self.width, height: value)
        }
    }

    public var left: CGFloat {
        get {
            return self.x
        } set(value) {
            self.x = value
        }
    }

    public var right: CGFloat {
        get {
            return self.x + self.width
        } set(value) {
            self.x = value - self.width
        }
    }
     
    public var top: CGFloat {
        get {
            return self.y
        } set(value) {
            self.y = value
        }
    }
     
    public var bottom: CGFloat {
        get {
            return self.y + self.height
        } set(value) {
            self.y = value - self.height
        }
    }
    
    // MARK: - maxX
    public var maxX : CGFloat {
        get {
            return self.frame.maxX
        }
    }
    
    // MARK: - maxY
    public var maxY : CGFloat {
        get {
            return self.frame.maxY
        }
    }
    
    // MARK: - minY
    public var minY : CGFloat {
        get {
            return self.frame.minY
        }
    }
    
    func mediateY(_ subViewHeight:CGFloat) -> CGFloat {
        return ((self.height - subViewHeight)/2)
    }
    
    func mediateX(_ subViewWhite:CGFloat) -> CGFloat {
        return ((self.width - subViewWhite)/2)
    }
     
    public var origin: CGPoint {
        get {
            return self.frame.origin
        } set(value) {
            self.frame = CGRect(origin: value, size: self.frame.size)
        }
    }
     
    public var centerX: CGFloat {
        get {
            return self.center.x
        } set(value) {
            self.center.x = value
        }
    }

    public var centerY: CGFloat {
        get {
            return self.center.y
        } set(value) {
            self.center.y = value
        }
    }
     
    public var size: CGSize {
        get {
            return self.frame.size
        } set(value) {
            self.frame = CGRect(origin: self.frame.origin, size: value)
        }
    }
}

